﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.Model;
using Autofac.Integration.Mvc;

namespace CNKI.TPI.Web.UI.Filters
{
    public class CustAuthAttribute : AuthorizeAttribute
    {

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string controller = ((System.Web.Mvc.MvcHandler)(httpContext.CurrentHandler)).RequestContext.RouteData.Values["controller"].ToString();
            string action = ((System.Web.Mvc.MvcHandler)(httpContext.CurrentHandler)).RequestContext.RouteData.Values["action"].ToString();
            bool anonymousControlFlag = ConfigHelper.IsAnonymousControlEnabled();
            string anonymousUsername = ConfigHelper.GetAnonymousAccount();
            string currentUsername = "";
            bool result = false;
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            if ("Login".Equals(action))
            {
                return true;
            }

            if (anonymousControlFlag && !SessionHelper.IsUserInfoExsit())
            {
                IUserService userService = AutofacDependencyResolver.Current.GetService<IUserService>();
                LoginUserInfo userinfo = userService.ValidateUser(anonymousUsername, "", false);
                if (null != userinfo && userinfo.status == LoginUserInfo.MessageFlage.Success)
                {
                    SessionHelper.SetUserInfo(userinfo);
                    currentUsername = userinfo.UserCode;
                }
                else
                {
                    return false;
                }
            }
            if (SessionHelper.IsUserInfoExsit())
            {
                currentUsername = SessionHelper.GetUserInfo().UserCode;
            }

            //没有角色控制
            if (Roles == null || Roles.Length == 0)
            {
                result = true;
            }
            //未登录
            else if (!SessionHelper.IsUserInfoExsit())
            {
                result = false;
            }
            //按照角色定义控制
            else if (IsUserMatchRole(httpContext) && CheckDBRight(httpContext, controller, action))
            {
                result = true;
            }
            return result;
        }

        private bool IsUserMatchRole(HttpContextBase httpContext)
        {
            bool result = false;
            try
            {
                LoginUserInfo userInfo = SessionHelper.GetUserInfo();
                bool anonymousControlFlag = ConfigHelper.IsAnonymousControlEnabled();
                string anonymousUsername = ConfigHelper.GetAnonymousAccount();
                if (userInfo != null)
                {
                    //获得当前登录用户角色
                    var roleList = userInfo.Role.Select(c => c.Name);
                    var actionRoles = Roles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (actionRoles.Contains("LoginUser"))
                    {
                        result = true;
                    }
                    else if (actionRoles.Contains("NoAnonymous"))
                    {
                        if (anonymousControlFlag && userInfo.UserCode == anonymousUsername)
                        {
                            result = false;
                        }
                        else
                        {
                            result = true;
                        }
                    }
                    else
                    {
                        foreach (string userRole in roleList)
                        {
                            if (actionRoles.Contains(userRole))
                            {
                                result = true;
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName = filterContext.ActionDescriptor.ActionName;
            string roles = ActionRoles.GetActionRoles(actionName, controllerName);
            this.Roles = roles;
            base.OnAuthorization(filterContext);
        }

        private bool CheckDBRight(HttpContextBase httpContext, string controller, string action)
        {
            bool result = true;
            try
            {
                int dbID = 0;
                string dbcode = "";
                bool checkSubmitRight = false;
                switch (controller.ToUpper())
                {
                    case "SINGLESEARCH":
                        if ("INDEX".Equals(action.ToUpper()))
                        {
                            dbID = int.Parse(httpContext.Request.Params["id"]);
                        }
                        break;
                    case "TOPICSINGLESEARCH":
                        if ("INDEX".Equals(action.ToUpper()))
                        {
                            dbID = int.Parse(httpContext.Request.Params["id"]);
                        }
                        break;
                    case "TOPICMULTISEARCH":
                        if ("INDEX".Equals(action.ToUpper()))
                        {
                            dbID = int.Parse(httpContext.Request.Params["id"]);
                        }
                        break;
                    case "DETAIL":
                        if ("INDEX".Equals(action.ToUpper()))
                        {
                            dbID = int.Parse(httpContext.Request.Params["dbID"]);
                        }
                        break;
                    case "TOPICDETAIL":
                        if ("INDEX".Equals(action.ToUpper()))
                        {
                            dbID = int.Parse(httpContext.Request.Params["dbID"]);
                        }
                        break;
                    case "SUBMITONLINE":
                        if ("INDEX".Equals(action.ToUpper()))
                        {
                            dbcode = httpContext.Request.Params["dbCode"].ToString();
                            checkSubmitRight = true;
                        }
                        break;
                    case "SUBMIT":
                        if ("REVIEWINDEX".Equals(action.ToUpper()))
                        {
                            dbID = int.Parse(httpContext.Request.Params["dbID"]);
                        }
                        break;
                    case "FILE":
                        if ("GETFIRSTDIGITALFILE".Equals(action.ToUpper()))
                        {
                            dbID = int.Parse(httpContext.Request.Params["dbID"]);
                        }
                        break;
                }

                if (dbID != 0 && SessionHelper.GetUserOperateFunc(dbID) == 0)
                {
                    result = false;
                }
                if ((!string.IsNullOrEmpty(dbcode)) && SessionHelper.GetUserOperateFunc(dbcode) == 0)
                {
                    result = false;
                }
                if (result && checkSubmitRight && (!SessionHelper.HasSubmitRight(dbcode)))
                {
                    result = false;
                }
            }
            catch(Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        //protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
        //{
        //    //filterContext.HttpContext.Response.Write("<script>alert('请登录！');</script>");

        //    //保持当前页
        //    //if (null != filterContext.HttpContext.Request.UrlReferrer)
        //    //{
        //    //    filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.AbsolutePath);
        //    //}
        //    //else
        //    //{
        //    //    filterContext.Result = new RedirectResult("/");
        //    //}

        //    //跳转到登录页面
        //    if (null != filterContext.HttpContext.Request.UrlReferrer)
        //    {
        //        filterContext.Result = new RedirectResult("~/Account/Login?ReturnUrl=" + filterContext.HttpContext.Request.Url.AbsolutePath);
        //        filterContext.HttpContext.Request.
        //    }
        //    else
        //    {
        //        filterContext.Result = new RedirectResult("~/Account/Login");
        //    }

        //}
    }
}